//
//  XCComposeViewController.swift
//  小陈微博Swift用纯代码创建
//
//  Created by 小陈 on 16/3/9.
//  Copyright © 2016年 小陈. All rights reserved.
//

import UIKit
import SnapKit
class XCComposeViewController: UIViewController {
///微博提示文字的长度
    private let statusTipLength = 25
    
    override func viewDidLoad() {
        super.viewDidLoad()
        view.backgroundColor = UIColor.whiteColor()
        
         prepareUI()
       
        
         NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardWillChangeFrame:", name: UIKeyboardWillChangeFrameNotification, object: nil)
        
    }
    func prepareUI(){
        setUpNavigationBar()
        
        setUptextView()// 先加这个在加 setUpTollBar 具体的理解开老师的代码
        
        setUpToolBar()
        
        setUpLengthTipLable()
    }
    
    
    
    override func viewDidAppear(animated: Bool) {
        super.viewDidAppear(animated)
        TextView.becomeFirstResponder()
    }
    
    /// 移除通知
    deinit{
        NSNotificationCenter.defaultCenter().removeObserver(self)
    }
    func text(){
        
        /*
        NSontication NSConcreteNotification 0x7ffdc5c447f0 {name = UIKeyboardWillChangeFrameNotification; userInfo = {
        UIKeyboardAnimationCurveUserInfoKey = 7;
        UIKeyboardAnimationDurationUserInfoKey = "0.25";
        UIKeyboardBoundsUserInfoKey = "NSRect: {{0, 0}, {375, 225}}";
        UIKeyboardCenterBeginUserInfoKey = "NSPoint: {187.5, 779.5}";
        UIKeyboardCenterEndUserInfoKey = "NSPoint: {187.5, 554.5}";
        UIKeyboardFrameBeginUserInfoKey = "NSRect: {{0, 667}, {375, 225}}";
        UIKeyboardFrameEndUserInfoKey = "NSRect: {{0, 442}, {375, 225}}";
        UIKeyboardIsLocalUserInfoKey = 1;
        }}
        
        
        
        NSontication NSConcreteNotification 0x7ffdc365db10 {name = UIKeyboardWillChangeFrameNotification; userInfo = {
        UIKeyboardAnimationCurveUserInfoKey = 7;
        UIKeyboardAnimationDurationUserInfoKey = "0.25";
        UIKeyboardBoundsUserInfoKey = "NSRect: {{0, 0}, {375, 225}}";
        UIKeyboardCenterBeginUserInfoKey = "NSPoint: {187.5, 554.5}";
        UIKeyboardCenterEndUserInfoKey = "NSPoint: {187.5, 779.5}";
        UIKeyboardFrameBeginUserInfoKey = "NSRect: {{0, 442}, {375, 225}}"; // 开始的frame
        UIKeyboardFrameEndUserInfoKey = "NSRect: {{0, 667}, {375, 225}}";   // 结束的frame
        UIKeyboardIsLocalUserInfoKey = 1;
        }}
        */
        
    }
    func keyboardWillChangeFrame(Notification:NSNotification){
       
        let duration = Notification.userInfo!["UIKeyboardAnimationDurationUserInfoKey"]!.doubleValue
        
        let frame = Notification.userInfo!["UIKeyboardFrameEndUserInfoKey"]!.CGRectValue

        let ToolBarBottonCom = -(UIScreen.height - frame!.origin.y) // 键盘向上移的frame是负数
        ToolBar.snp_updateConstraints { (make) -> Void in
            make.bottom.equalTo(view).offset(ToolBarBottonCom)
        }
        
        UIView.animateWithDuration(duration) { () -> Void in
            self.view.layoutIfNeeded()
            
        }
        
    }
    
    
    func setUpLengthTipLable(){
        /// 添加控件
        view.addSubview(lengthTipLabel)
        
        lengthTipLabel.text = String(statusTipLength)
        
        lengthTipLabel.sizeToFit()
        
       // 添加约束
        lengthTipLabel.snp_makeConstraints { (make) -> Void in
            make.bottom.equalTo(ToolBar.snp_top).offset(-4)
            make.trailing.equalTo(view).offset(-4)
        }
    }
    
    // 自动调整scrollViewInsets
    // 前提1:scrollView或子类所在的view是在导航栏里面
    // 前提2:scrollView或子类必须是控制器的view或者scrollView或子类是控制器view的第一个子view,在依次循环
    //       automaticallyAdjustsScrollViewInsets = true
    func setUptextView(){
        /// 添加控件
        view.addSubview(TextView)
        /// 添加约束
        TextView.snp_makeConstraints { (make) -> Void in
            make.edges.equalTo(view)
        }
    }
    
    func setUpNavigationBar(){
      setUpBarButtonItem()
      setUPTitle()
     
    }
    
    func setUpToolBar(){
        view.addSubview(ToolBar)
        
        /// 添加约束
        ToolBar.snp_makeConstraints { (make) -> Void in
            make.leading.trailing.bottom.equalTo(view)
        }
        
        let itemSettings = [["imageName": "compose_toolbar_picture", "action": "picture"],
            ["imageName": "compose_trendbutton_background", "action": "trend"],
            ["imageName": "compose_mentionbutton_background", "action": "mention"],
            ["imageName": "compose_emoticonbutton_background", "action": "emoticon:"],
            ["imageName": "compose_add_background", "action": "add"]]
        // 创建空数组 // 系统自带的items 是不能添加数据的
        ToolBar.items = [UIBarButtonItem]()
        for dict in itemSettings{
            
            let imageName = dict["imageName"]!
            
            let item = UIBarButtonItem(ImageName: imageName)
            
            
            
            /// 添加按钮的点击事件
            let barButton = item.customView as! UIButton
            ToolBar.items?.append(item)

              // action 可以直接放入String，如果是变量或者常量需要使用Selector
            barButton.addTarget(self, action: Selector(dict["action"]!), forControlEvents: UIControlEvents.TouchUpInside)
            
            ToolBar.items?.append(UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.FlexibleSpace, target: nil, action: nil))
        }
        
        ToolBar.items?.removeLast()

    }
  /// 在Swift中 调用常量或者变量的私有方法需要添加 @objec
@objc private func picture(){
        print("你点击了 图片 按钮")
    }
 @objc private   func trend(){
           print("你点击了 # 按钮")
    }
  @objc private  func mention(){
           print("你点击了 @ 按钮")
    }
    @objc private func emoticon(button:UIButton){
           print("你点击了 表情 按钮")
    // 先退出系统的键盘
    TextView.resignFirstResponder()
   TextView.inputView = TextView.inputView == nil ? emoticonKeyboard : nil
    let imageNormal :UIImage?
    let imageheight :UIImage?
    if TextView.inputView == nil {
    imageNormal = UIImage(named: "compose_keyboardbutton_background")
        imageheight = UIImage(named: "compose_keyboardbutton_background_highlighted")
    }else{
        
        imageNormal = UIImage(named: "compose_emoticonbutton_background")
        imageheight = UIImage(named: "compose_emoticonbutton_background_highlighted")
    }
        button.setImage(imageNormal, forState: UIControlState.Normal)
        button.setImage(imageheight, forState: UIControlState.Highlighted)
        
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (Int64)(250 * USEC_PER_SEC)),  dispatch_get_main_queue()) { () -> Void in
        
        // 弹出自定义的键盘
        TextView.becomeFirstResponder()
    }
    
    
//    
//    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (Int64)(250 * USEC_PER_SEC)), dispatch_get_main_queue()){() -> Void in
//    
//};
    
    }
   @objc private func add(){
           print("你点击了 + 按钮")

    }
    
    
    
    func setUPTitle(){
        let prefix = "发微博"
//        XCUSerAccountViewModel.sharedInstance.userAccount?.screen_name = nil
        if (XCUSerAccountViewModel.sharedInstance.userAccount?.screen_name != nil) {
        let name = XCUSerAccountViewModel.sharedInstance.userAccount?.screen_name

        let title = prefix + "\n" + name!
            
            let lable = UILabel()
            lable.numberOfLines = 0
            lable.font = UIFont.systemFontOfSize(14)
            lable.text = title
            lable.textAlignment = NSTextAlignment.Center
   let attrText = NSMutableAttributedString(string: title)
            
     let range = (title as NSString).rangeOfString(name!)
            
            attrText.addAttributes([NSForegroundColorAttributeName:UIColor.lightGrayColor(),NSFontAttributeName:UIFont.systemFontOfSize(12)], range: range)
            
            
            
            lable.sizeToFit()
            navigationItem.titleView = lable
            
         lable.attributedText = attrText
        }else{
          navigationItem.title = prefix
        }
        
        
    }
    
    
    func setUpBarButtonItem(){
      navigationItem.leftBarButtonItem = UIBarButtonItem(title: "取消", style: UIBarButtonItemStyle.Plain, target:self, action: "close")
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "发送", style: UIBarButtonItemStyle.Plain, target: self, action: "send")
        // 刚开始设置navigation右边的按钮的状态不可点击
        navigationItem.rightBarButtonItem?.enabled = false
        
    }
    func close(){
        print( "点击了取消")
        // 取消键盘成为第一响应者
        TextView.resignFirstResponder()
        dismissViewControllerAnimated(true, completion: nil)
    }
    
    
    func send(){
//        print( "点击了发微博")
        let status = TextView.emoticonText()
        
        // 获取现有文本的长度
        let length = TextView.emoticonText().characters.count
        // 计算剩余文本的长度
        let lastLength = statusTipLength - length
        
        
        
      XCStatusViewModel.sendStatus(status) { (error) -> () in
        if error != nil{
            print("error ：\(error)")
            return
        }
        print("发送微博成功")
        }
        
    }
    
    
    
    lazy var ToolBar:UIToolbar = {
       let toolBar = UIToolbar()
        toolBar.backgroundColor = UIColor.redColor()
        
        return toolBar
    }()
    
    
    lazy var TextView:XCPlaceholderTextView = {
       let tv = XCPlaceholderTextView()
        
//        tv.text  = "分享微博......"
        tv.backgroundColor = UIColor.darkGrayColor()
        tv.font = UIFont.systemFontOfSize(18)
        tv.alwaysBounceVertical = true/// 下拉有弹簧效果
//        tv.alwaysBounceHorizontal = true // 左右拉的弹簧效果
        
        tv.keyboardDismissMode = UIScrollViewKeyboardDismissMode.OnDrag
        
        tv.XCplaceholderTextView = "分享微博..."
        
        tv.delegate = self
        return tv
    }()
    
    /// 表情键盘
    private lazy var emoticonKeyboard: CZEmoticonKeyboard = {
        let view = CZEmoticonKeyboard(frame: CGRect(origin: CGPointZero, size: CGSize(width: UIScreen.mainScreen().bounds.width, height: 216)))
        
        view.textView = self.TextView
        
        return view
        }()
    
    /// 微博长度提示lable
    private lazy var lengthTipLabel :UILabel = UILabel(textColor: UIColor.lightGrayColor(), font: 12)
  
}

// MARK : - 扩展 UITextViewDelegate 的代理方法监听 导航
extension XCComposeViewController : UITextViewDelegate{
    func textViewDidChange(textView: UITextView) {
     
        navigationItem.rightBarButtonItem?.enabled = TextView.hasText()
        
    /*==========emoticonText()方法是计算view的的字符串和表情的长度=====================*/
        
        // 获取现有文本的长度
        let length = TextView.emoticonText().characters.count
        // 计算剩余文本的长度
        let lastLength = statusTipLength - length
        
        lengthTipLabel.text = String(lastLength)
        
         lengthTipLabel.textColor = lastLength > 0 ? UIColor.lightGrayColor() : UIColor.redColor()
    }
}
